package com.zl.websocket.config.redis;

import java.util.Iterator;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * RedisTemplate配置器
 * 
 * @author WY
 * @date 2017-03-21
 */
@Configuration
public class RedisConfiguration {

	@Autowired
	private JedisConnectionFactory jedisConnectionFactory;

	@Autowired
	private ThreadPoolTaskExecutor threadPoolTaskExecutor;

	@Primary
	@Bean(name = "redisTemplate")
	public RedisTemplate<?, ?> redisTemplate() {
		RedisTemplate<byte[], byte[]> template = new RedisTemplate<byte[], byte[]>();
		template.setConnectionFactory(jedisConnectionFactory);
		GenericJackson2JsonRedisSerializer jsonSerializationRedisSerializer = new GenericJackson2JsonRedisSerializer();
		template.setKeySerializer(template.getStringSerializer());
		template.setValueSerializer(jsonSerializationRedisSerializer);
		template.setHashKeySerializer(template.getStringSerializer());
		template.setHashValueSerializer(jsonSerializationRedisSerializer);
		template.afterPropertiesSet();
		return template;
	}
	
	/**
	 * redis channle订阅
	 * @param redisMessageListener
	 * @return
	 */
	@Bean
//	@ConditionalOnBean(RedisMessageListener.class)
	public RedisMessageListenerContainer redisMessageListenerContainer(
			@Autowired(required=false) Map<String, RedisMessageListener> redisMessageListener) {
		if(null == redisMessageListener || redisMessageListener.isEmpty()) {
			return null;
		}
		try {
			RedisMessageListenerContainer container = new RedisMessageListenerContainer();
			container.setConnectionFactory(jedisConnectionFactory);
			container.setTaskExecutor(threadPoolTaskExecutor);
			for (Iterator<String> it = redisMessageListener.keySet().iterator(); it.hasNext();) {
				RedisMessageListener listener = redisMessageListener.get(it.next());
				container.addMessageListener(listener, listener.getTopics());
			}
			return container;
		} finally {
			threadPoolTaskExecutor.execute(new Runnable() {
				@Override
				public void run() {
					try {
						Thread.sleep(5000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					for (Iterator<String> it = redisMessageListener.keySet().iterator(); it.hasNext();) {
						redisMessageListener.get(it.next()).afterListen();
					}
				}
			});
		}
	}
}
